const express = require('express');
const path = require('path');
const url = require('url');
const session = require('express-session');
const template = require('art-template');
const dateFormat = require('dateformat');

const app = express();

//数据库
require('./model/connect.js');
// require('./model/user');

//配置session
app.use(session({secret: 'secret key'}));

app.set('views',path.join(__dirname,'views'));
app.set('view engine','art');
app.engine('art',require('express-art-template'));

//向模版内部导入 dateFormate 方法
template.defaults.imports.dateFormat = dateFormat

//获取 body 参数插件
app.use(express.urlencoded({extended: false}))

//开放静态资源
app.use(express.static(path.join(__dirname,'public')));

//引入路由模块
const home = require('./route/home');
const admin = require('./route/admin');

//拦截请求判断登录状态
app.use('/admin',require('./middleware/loginGuard'));

//匹配对应路径
app.use('/home',home);
app.use('/admin',admin);

app.use((err,req,res,next) => {
    const result = JSON.parse(err);
    let params = [];

    for (let attr in result) {
        if(attr != 'path') {
            params.push(attr + '=' + result[attr]);
        }
    }
    res.redirect(`${result.path}?${params.join('&')}`);
})


app.listen(80,() => {
    console.log('服务器连接成功');
})